//
//  ShopMyInfoViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/5/18.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "ShopMyInfoViewController.h"
#import "ShopMyInfoTableViewCell.h"
#import "DataSelectView.h"
#import "LoginTypeView.h"
#import "PrCodeView.h"
#import "ShopMapViewController.h"
#import "ShopMainViewController.h"
#import "DataSelectView.h"
#import "ShopMainPageViewController.h"
#import "PayViewController.h"
#import "ScanViewController.h"

@interface ShopMyInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSDictionary *dic;
    UIImage *headerImage;
    UIImage *iconImage;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UIView *footerView;

@property (nonatomic,strong) UIImageView *headerImgView;
@property (nonatomic,strong) UIImageView *iconImgView;

@property (nonatomic,strong) UIButton *saveButton;

@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSDictionary *dataDictionary;

@end

//网络
@implementation ShopMyInfoViewController (NetWorking)

- (void)getData{
    if ([[UserModel sharedInstanced].s_id isEqualToString:@""]) {
        return;
    }
    [self showprogressHUD];
    NSDictionary *parameters = @{@"s_id":[UserModel sharedInstanced].s_id};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Mobile/displayStoreInformationThroughStoreID.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            dic = responseObject[@"obj"];
            self.dataArray[0][@"key"] = dic[@"s_name"];
            self.dataArray[1][@"key"] = dic[@"open_time"];
            self.dataArray[2][@"key"] = dic[@"s_mobile"];
            self.dataArray[3][@"key"] = dic[@"s_address"];
            self.dataArray[4][@"key"] = dic[@"describe"];
            [self.headerImgView sd_setImageWithURL:[NSURL URLOffsetIPWithString:dic[@"first_picture"]] placeholderImage:[UIImage imageNamed:@"button_mapadd"]];
            self.headerImgView.contentMode = UIViewContentModeScaleAspectFill;
            [self.iconImgView sd_setImageWithURL:[NSURL URLOffsetIPWithString:dic[@"s_logo"]] placeholderImage:[UIImage imageNamed:@"button_mapadd"]];
            self.iconImgView.contentMode = UIViewContentModeScaleAspectFill;
            [self.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)getAddData{
    [self showprogressHUD];
    
    NSDictionary *parameters = @{@"id":[UserModel sharedInstanced].userId,
                                 @"s_name":self.dataArray[0][@"key"],
                                 @"open_time":self.dataArray[1][@"key"],
                                 @"s_mobile":self.dataArray[2][@"key"],
                                 @"s_address":self.dataArray[3][@"key"],
                                 @"describe":self.dataArray[4][@"key"],
                                 @"s_longitude":[UserModel sharedInstanced].longitude,
                                 @"s_latitude":[UserModel sharedInstanced].latitude};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Mobile/newStore.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (headerImage) {
            NSData *data = UIImageJPEGRepresentation(self.headerImgView.image, .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data name:@"file1" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        }
        if (iconImage) {
            NSData *data = UIImageJPEGRepresentation(self.iconImgView.image, .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data name:@"file2" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        if ([responseObject[@"ResponseStatus"] isEqualToString:@"0"]) {
//            [self.view makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
//                [self.navigationController popViewControllerAnimated:YES];
//            }];
//        }else{
            ShowMessage(responseObject[@"msg"]);
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            [UserModel sharedInstanced].s_id = [NSString stringWithFormat:@"%@",responseObject[@"obj"]];
        }
//        }
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];

}

- (void)getUdateData{
    [self showprogressHUD];
    
    NSDictionary *parameters = @{@"s_id":[UserModel sharedInstanced].s_id,
                                 @"s_name":self.dataArray[0][@"key"],
                                 @"open_time":self.dataArray[1][@"key"],
                                 @"s_mobile":self.dataArray[2][@"key"],
                                 @"s_address":self.dataArray[3][@"key"],
                                 @"describe":self.dataArray[4][@"key"],
                                 @"s_longitude":[UserModel sharedInstanced].longitude,
                                 @"s_latitude":[UserModel sharedInstanced].latitude};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Mobile/modifyStoreInformation.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
      
            NSData *data = UIImageJPEGRepresentation(self.headerImgView.image, .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data name:@"file1" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
      
            NSData *data1 = UIImageJPEGRepresentation(self.iconImgView.image, .1);
            NSTimeInterval time1 = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data1 name:@"file2" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time1] mimeType:@"image/jpeg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        if ([responseObject[@"ResponseStatus"] isEqualToString:@"0"]) {
        //            [self.view makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
        //                [self.navigationController popViewControllerAnimated:YES];
        //            }];
        //        }else{
        ShowMessage(responseObject[@"msg"]);
        //        }
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
    
}

@end

//UI
@implementation ShopMyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"店铺信息";
    [self.view addSubview:self.tableView];
    //定位按钮
    UIButton * leftButton = [[UIButton alloc]init];
    leftButton.size = CGSizeMake(40, 40);
    [leftButton setImage:[UIImage imageNamed:@"root_address"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    // 让按钮内部的所有内容左对齐
    leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    //工作状态
    UIButton * workStateBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60/WIDTH_5S_SCALE, 20/WIDTH_5S_SCALE)];
    workStateBtn.layer.cornerRadius = workStateBtn.height/2;
    workStateBtn.layer.masksToBounds = YES;
    workStateBtn.titleLabel.font = DEF_FontSize_13;
    [workStateBtn setBackgroundImage:[UIImage imageNamed:@"shangbanzhong"] forState:UIControlStateNormal];
    [workStateBtn setBackgroundImage:[UIImage imageNamed:@"yidayang"] forState:UIControlStateSelected];
    [workStateBtn addTarget:self action:@selector(workStateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    [workStateBtn setTitle:@"上班中" forState:UIControlStateNormal];
//    workStateBtn.layer.borderColor = getColor(@"ff02fe").CGColor;
//    workStateBtn.layer.borderWidth = 0.5;
    UIBarButtonItem * workStateItem = [[UIBarButtonItem alloc] initWithCustomView:workStateBtn];
    self.navigationItem.leftBarButtonItems = @[item, workStateItem];
    //店铺首页按钮
    UIButton * rightButton = [[UIButton alloc]init];
    rightButton.size = CGSizeMake(50, 20);
    [rightButton setTitle:@"店铺首页" forState:UIControlStateNormal];
    [rightButton.titleLabel setFont:DEF_FontSize_11];
    rightButton.layer.masksToBounds = YES;
    rightButton.layer.cornerRadius = 3;
    rightButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    rightButton.layer.borderWidth = 1;
    [rightButton addTarget:self action:@selector(rightBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //扫描按钮
    UIButton * scanBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [scanBtn setImage:[UIImage imageNamed:@"saoyisao"] forState:UIControlStateNormal];
    [scanBtn addTarget:self action:@selector(scanBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * scanItem = [[UIBarButtonItem alloc] initWithCustomView:scanBtn];
    //设置barbutton
//    self.navigationItem.leftBarButtonItem = item;
    self.navigationItem.rightBarButtonItems = @[rightItem, scanItem];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

#pragma mark - Event
- (void)workStateBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
}

- (void)leftBarButtonItemClick{
    ShopMapViewController *vc = [[ShopMapViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)rightBarButtonItemClick{
    [self.view endEditing:YES];
//    ShopMainViewController *vc = [[ShopMainViewController alloc] init];
    
    ShopMainPageViewController *vc = [[ShopMainPageViewController alloc] init];
    [vc setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:vc animated:YES];
    
    //付款
//    PayViewController * vc = [[PayViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scanBtnClick:(UIButton *)sender{
    NSLog(@"扫描");
    ScanViewController * scanVC = [[ScanViewController alloc] init];
    [self.navigationController pushViewController:scanVC animated:YES];
}

- (void)shopUploadBgImgEvent:(UITapGestureRecognizer *)sender{
    [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
        self.headerImgView.image = img;
        headerImage = img;
        self.headerImgView.contentMode = UIViewContentModeScaleAspectFill;
    }];
}

- (void)shopUploadIconEvent:(UITapGestureRecognizer *)sender{
    [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
        self.iconImgView.image = img;
        iconImage = img;
        self.iconImgView.contentMode = UIViewContentModeScaleAspectFill;
    }];
}

- (void)saveInfo{
    NSLog(@"保存信息");
    [self.view endEditing:YES];
    if ([[UserModel sharedInstanced].s_id isEqualToString:@""]) {
        if (!headerImage) {
            ShowMessage(@"请选择店铺首图");
            return;
        }
        if (!iconImage) {
            ShowMessage(@"请选择店铺logo");
            return;
        }
    }
    for (int i = 0 ; i < self.dataArray.count; i ++) {
            if ([self.dataArray[i][@"key"] isEqualToString:@"无"]) {
                NSString *str = self.dataArray[i][@"ph"];
                ShowMessage(str);
                return;
            }
    }
    if ([[UserModel sharedInstanced].s_id isEqualToString:@""]) {
        [self getAddData];
    }else{
        [self getUdateData];
    }
    
}
#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShopMyInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShopMyInfoTableViewCell class])];
    cell.indexPath = indexPath;
    cell.dataDictionary = self.dataArray[indexPath.row];
    cell.getTextString = ^(NSString *str) {
        self.dataArray[indexPath.row][@"key"] = str;
        [self.tableView reloadData];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 1) {
        DataSelectView *view = [[DataSelectView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [view show];
        view.selectHandle = ^(NSString *str) {
            self.dataArray[indexPath.row][@"key"] = str;
            [self.tableView reloadData];
        };
    }
}

#pragma mark - set & get

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64 - 60) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = self.footerView;
        _tableView.tableHeaderView = self.headerView;
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ShopMyInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ShopMyInfoTableViewCell class])];
        _tableView.backgroundColor = [UIColor whiteColor];
    }
    return _tableView;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 230/WIDTH_5S_SCALE)];
        _headerView.backgroundColor = [UIColor whiteColor];
        [_headerView addSubview:self.headerImgView];
        [_headerView addSubview:self.iconImgView];
    }
    return _headerView;
}

- (UIImageView *)iconImgView{
    if (!_iconImgView) {
        _iconImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 165/WIDTH_5S_SCALE+15, 48/WIDTH_5S_SCALE, 48/WIDTH_5S_SCALE)];
        _iconImgView.center = CGPointMake(SCREEN_WIDTH/2., _iconImgView.centerY);
        _iconImgView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _iconImgView.layer.borderWidth = 2;
        _iconImgView.userInteractionEnabled = YES;
        _iconImgView.contentMode = UIViewContentModeCenter;
        _iconImgView.backgroundColor = getColor(@"f1f2f6");
        _iconImgView.image = [UIImage imageNamed:@"button_mapadd"];
        _iconImgView.layer.masksToBounds = YES;
        [_iconImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shopUploadIconEvent:)]];
    }
    return _iconImgView;
}

- (UIImageView *)headerImgView{
    if (!_headerImgView) {
        _headerImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 165/WIDTH_5S_SCALE)];
        _headerImgView.backgroundColor = getColor(@"f1f2f6");
        _headerImgView.contentMode = UIViewContentModeCenter;
        _headerImgView.image = [UIImage imageNamed:@"button_mapadd"];
        _headerImgView.userInteractionEnabled = YES;
        [_headerImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shopUploadBgImgEvent:)]];
        _headerImgView.layer.masksToBounds = YES;
    }
    return _headerImgView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
        [_footerView addSubview:self.saveButton];
    }
    return _footerView;
}

- (UIButton *)saveButton{
    if(!_saveButton){
        _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _saveButton.frame = CGRectMake((SCREEN_WIDTH - 200)/2, 15, 200, 30);
        _saveButton.backgroundColor = getColor(mainColor);
        [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
        _saveButton.layer.masksToBounds = YES;
        _saveButton.layer.cornerRadius = 15;
        [_saveButton addTarget:self action:@selector(saveInfo) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveButton;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = @[@{@"title":@"店铺名称",
                         @"ph":@"请输入店铺名称",
                         @"key":@"无"}.mutableCopy,
                       @{@"title":@"开店时间",
                         @"ph":@"请选择开店时间",
                         @"key":@"无"}.mutableCopy,
                       @{@"title":@"联系方式",
                         @"ph":@"请输入联系方式",
                         @"key":@"无"}.mutableCopy,
                       @{@"title":@"公司地址",
                         @"ph":@"请输入公司地址",
                         @"key":@"无"}.mutableCopy,
                       @{@"title":@"店铺描述",
                         @"ph":@"请输入店铺描述",
                         @"key":@"无"}.mutableCopy,
                      ].mutableCopy;
    }
    return _dataArray;
}

- (NSDictionary *)dataDictionary{
    if (!_dataDictionary) {
        _dataDictionary = @{};
    }
    return _dataDictionary;
}

@end
